< previous page page_114 next page >

Page 114
Listing 5.1. continued
    If InStr(strValid, Chr(KeyAscii)) = 0 Then
        KeyAscii = 0
    End If
    '
End Sub
In Listing 5.1, you declared a string variable that holds the list of valid keys. The next line loads the string with the valid keys for this field, and the next line checks to see whether the key pressed is in the string of valid keys. It does this by converting the numeric value passed by Visual Basic 5 in the KeyAscii parameter (the ASCII value of the key pressed) into a readable character using the Visual Basic 5 Chr function and searching for the result in the list of valid keys in the cValid string. If the key pressed is not in the cValid string, the keystroke is set to 0. Setting the keystroke to 0 is telling Visual Basic 5 to pretend nothing was ever typed!
Now save and run the program. No matter what keys you type, only the numerals 0 through 9 appear in the textbox. You have filtered out everything but numerals. You may also notice that keystrokes, such as the backspace and delete keys, no longer work! You've told Visual Basic 5 to ignore them. You can fix that by adding a statement that checks to see whether the keystroke is a control code. Control codes are used in Visual Basic 5 to indicate that the key the user pressed was not a printable character but a keyboard control character. Common control characters are the Escape key, the Return key, the Backspace key, and so on.
You can also add any other characters to the validity list if you like. For example, you probably want to be able to enter a minus sign, a plus sign, and a decimal point in this number field. To do this, all you need to do is add those three characters to the cValid string. Your program code should now look like Listing 5.2.
Type.gifListing 5.2. The KeyPress event with control characters.
Private Sub txtNumber_KeyPress(KeyAscii As Integer)
    '
    Dim strValid As String
    '
    strValid = "0123456789+-."
    '
    If KeyAscii > 26 Then ' if it's not a control code
        If InStr(strValid, Chr(KeyAscii)) = 0 Then
            KeyAscii = 0
        End If
    End If
    '
End Sub

 
< previous page page_114 next page >

If you like this book, buy it!